var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
var willLoading = false;
var groupLoading = false;
var giftLoading = false;
function checkorder(orderid,that){
	app.util.request({
		url: 'entry/wxapp/checkorder',
		data: {
			m: 'junsion_challeng',
			orderid:orderid
		},
		cachetime: 0,
		success: function (res) {
			var data = res.data;
			if(data == 1){
				that.setData({
					openChance: !that.data.openChance,
					challeng_num: 1
				});
				wx.showModal({
					title:'支付成功',
					showCancel:false,
					success: function(res) {
						that.onLoad();
					}
				});
			}else{
				setTimeout(function(){
					checkorder(orderid,that);
				},1000);
			}
		},
	})
}

/*checkpage2 start */
const defaultLogName = {
  work: '工作',
  rest: '休息'
}
const actionName = {
  stop: '停止',
  start: '开始'
}

const initDeg = {
  left: 45,
  right: -45,
}
const defaultTime = {
  defaultWorkTime: 25,
  defaultRestTime: 5
}

function formatTime(time, format) {
  let temp = '0000000000' + time
  let len = format.length
  return temp.substr(-len)
}
/*checkpage2 end */


Page({
	onShareAppMessage:function(){
	  var that = this;
	  var mid = that.data.mid;
	  var sharedata = that.data.shareData;
	  sharedata.path = 'challeng/pages/index/index?mid='+mid+'?gType='+that.data.gametype;
	  return {
		  title: sharedata.title,
	     // desc: sharedata.desc,
	      path: sharedata.path,
	      imageUrl:sharedata.pic,
	      success(res){
	    	  var shareTicket = res.shareTickets[0] // 获取 shareTicket
	    	  wx.getShareInfo({
	              shareTicket: shareTicket,
	              complete(res) {
	            	  app.util.request({
		    	        url: 'entry/wxapp/addnums',
		    	        data: {
		    	            m : 'junsion_challeng',
		    	            t : 1,
		    	            mid : that.data.openid,
		    	            iv : res.iv,
		    	            encryptedData : res.encryptedData,
		    	        },
		    	        success: function (res) {
		    	        	 if (res.data.code == 1) {
		                        that.setData({ challeng_num: parseInt(res.data.num)});
	                        	wx.showToast({
	                        		title:'次数\t+'+res.data.num,
	                        		icon:'none',
	                				mask:true,
	                				duration:1000
	                			});
		    	    	    }
		    	        	 else{
		    	        		 wx.showModal({title:res.data.msg,showCancel:false});
		    	        	}
		    	        }
		    	    }); 
	                
	              }
	          });
	      },
	      fail: function(res) {
	        // 转发失败
	    	  console.log(res);
	      }
	  }
  },
    data:{
    	openid:'',
    	nickname:'',
    	avatar:'',
        activeType:0,
        join_num:0,
        best_mems:{},
        will_mems:{},
        group_mems:{},
        agreement:false,
        price:{},
        gifts:{},
        challeng_num:1,
        get_share_num:0,
        agreetitle:'',
        rewardtitle:'',
        willpage:1,
        willHasMore:false,
        groupHasMore:false,
        giftpage:1,
        grouppage:1,
        scrollTop : 0,
        scrollHeight : 0,
        share_num : 0,
        mid:0,
        reward_tip:'',
        showReward:false,
        express_fee:0,
        face:{},
        initnum:0,
        libao:1,
        kefu_height:100,
        font:{},
        adv:{},
        sheight : 350,
        game:{},
        footer:{},
        currentPage:'',
        showIndex:2,
        gametype:0,
        options:{},
        game_status:{},
        gnum:0,
        gamelogo:'../../images/shoyte_beijingban.png',

        //page2 start
        remainTimeText: '',
        timerType: 'work',
        log: {},
        completed: false,
        isRuning: false,
        leftDeg: initDeg.left,
        rightDeg: initDeg.right,
        //page2 end
    },
    onLoad:function(options){
    	var that = this;
    	var scene = '';
        if(options.scene){
        	scene = decodeURIComponent(options.scene);
        }
    	var shareid = '';
    	if(options.mid){
    		shareid = decodeURIComponent(options.mid);
        }
    	var gobuy = '';
    	if(options.gobuy){
    		that.setData({openChance: !that.data.openChance});
    	}
    	that.setData({options: options});
    	wx.showLoading({title:'数据加载中...'});
    	app.sysInit(this,function(res){
          if(res.data == -1){
            wx.setNavigationBarTitle({ title: '任务计时' })
            var workTime = wx.getStorageSync('workTime');
            var restTime = wx.getStorageSync('restTime');
            if (!workTime) {
              var workTime = formatTime(defaultTime.defaultWorkTime, 'HH');
              var restTime = formatTime(defaultTime.defaultRestTime, 'HH');
              wx.setStorageSync('workTime', defaultTime.defaultWorkTime);
              wx.setStorageSync('restTime', defaultTime.defaultRestTime);
            }
            that.setData({
              workTime: workTime,
              restTime: restTime,
              remainTimeText: workTime + ':00'
            })
            that.setData({ showIndex: 1 });
            wx.hideLoading();
            return;
          }
        that.setData({ showIndex: 0 });
          app.getUserInfo(function (res) {
              var openid = res['openid'];
              wx.onUserCaptureScreen(function(res) {
          	    console.log('用户截屏了')
          	    app.util.request({
      	            url: 'entry/wxapp/BlackMem',
      	            data: {
      	              m: 'junsion_challeng',
      	              openid:openid,
      	              t: 1,
      	            },
      	            success: function (res) {
      	                wx.navigateBack({});
      	            },
      	        });
          	})
              
              var gametype = 0;
          	  if(options.gType && parseInt(that.data.check_status)==0){
          		  wx.setStorage({key:'gameType',data:options.gType});
          		  gametype = options.gType;
          		  that.setData({gametype: gametype});
          	  }
          	  else{
          		  var sysType = wx.getStorageSync('gameType');
              	  if(parseInt(sysType)>=0){
              		  gametype = sysType;
              		  that.setData({gametype: gametype});
              	  }
          	  }
              //获取分享内容
              app.getShareData(function(res){
              	that.setData({shareData:res.data});
              },openid,gametype);
              
              that.setData({openid:openid,nickname:res['nickname'],avatar:res['avatar']});
                app.util.request({
                url: 'entry/wxapp/index',
                data: {
                  m: 'junsion_challeng',
                  t: 1,
                  openid:openid,
                  scene:scene,
                  shareid:shareid,
                  openid: res['openid'],
                  nickname: res['nickname'],
                  avatar: res['avatar'],
                  game:gametype,
                },
                success: function (res) {
                  wx.hideLoading();
                  wx.setNavigationBarTitle({ title: res.data.title });
                  var data = {
                    join_num: res.data.join_num,
                    best_mems: res.data.best_mems,
                    will_mems: res.data.will_mems,
                    group_mems: res.data.group_mems,
                    price: res.data.price,
                    challeng_num: res.data.challeng_num,
                    get_share_num: res.data.get_share_num,
                    share_num: res.data.share_num,
                    mid: res.data.mid,
                    font: res.data.font,
                    express_fee: res.data.express_fee,
                    face: res.data.face,
                    initnum: res.data.initnum,
                    libao: res.data.libao,
                    adv: res.data.adv,
                    sort: res.data.sort,
                  };
                  if (res.data.msg) {
                    data['msg'] = res.data.msg;
                    data['marquee'] = { text: data.msg.txt };
                    var w = app.getWidth(data.msg.txt);
                    data[[`${'marquee'}.width`]] = w;
                    var s = data.msg.msgtime;
                    data[[`${'marquee'}.speed`]] = s > 5 ? s : 5;
                  }
                  if(!res.data.game.logo){
                	  res.data.game.logo=that.data.gamelogo
                  }
                  data['game'] = res.data.game;
                  that.setData(data);

                  if(res.data.face.custom){
                    wx.getImageInfo({
                      src: res.data.face.custom,
                      success: function (res) {
                        var rate = res.width / 100;
                        var height = res.height / rate;
                          that.setData({kefu_height:height});
                      }
                    })
                  }
                  if(res.data.will_mems.length<res.data.guts){
                    that.setData({willHasMore:true});
                  }
                  if(res.data.group_mems.length<5){
                    that.setData({groupHasMore:true});
                  }

                  if (res.data.clipboard){
                    wx.setClipboardData({
                      data: res.data.clipboard,
                    })
                  }

                  //获取unionid
                  if(res.data.getUnionid==1){
                    wx.getUserInfo({
                            success: function (wxInfo) {
                              app.util.request({
                                url: 'entry/wxapp/unionid',
                                data: {
                                  t: 1,
                                  openid: openid,
                                  iv: wxInfo.iv,
                                  encryptedData: wxInfo.encryptedData,
                                  m: 'junsion_challeng'
                                },
                                success: function (res) {
                                  if(res.data == 1){
                                    that.onLoad(options);
                                  }
                                }
                              });
                            }
                        });
                  }
                },
            });
                app.util.request({
                  url: 'entry/wxapp/gift',
                  data: {
                    m: 'junsion_challeng',
                    t: 1,
                  },
                  success: function (res) {
                    that.setData({
                      gifts : res.data.gifts,
                    });
                  },
                });
          });
        });
        wx.getSystemInfo({
            success:function(res){
                that.setData({
                    scrollHeight:res.windowHeight
                });
            }
        });
    },
    onShow:function(){
    var that = this
    app.getUserInfo(function (info) {
      app.util.request({
        url: 'entry/wxapp/ismem',
        data: { openid: info.openid, m: 'junsion_challeng' },
        success: function (res) {
          if (res.data == 1) {
            wx.navigateBack({});
          }
        },
      });
    });
  },
    goPre:function(){
    	var that = this;
    	var sort = that.data.sort;
    	var sysType = wx.getStorageSync('gameType');
    	var game_index = 0;
    	for(var i in sort){
    		if(sort[i]==sysType){
    			game_index = parseInt(i)-1;
    			break;
    		}
    	}
    	if(game_index<0){
    		var last_game = parseInt(that.data.gnum) - 1;
    		sysType = sort[last_game];
    	}
    	else{
    		sysType = sort[game_index];
    	}
    	wx.setStorage({
    		key:'gameType',
    		data:sysType,
    		success:function(){
    			that.data.options.gType='';
    			that.onLoad(that.data.options);
    		}
    	});
    },
    goNext:function(){
    	var that = this;
    	var sort = that.data.sort;
    	var sysType = wx.getStorageSync('gameType');
    	var game_index = 0;
    	for(var i in sort){
    		if(sort[i]==sysType){
    			game_index = parseInt(i)+1;
    			break;
    		}
    	}
    	var gnum = parseInt(that.data.gnum);
    	if(game_index>=gnum){
    		sysType = sort[0];
    	}
    	else{
    		sysType = sort[game_index];
    	}
    	wx.setStorage({
    		key:'gameType',
    		data:sysType,
    		success:function(){
    			that.data.options.gType='';
    			that.onLoad(that.data.options);
    		}
    	});
    },
    onMsg: function (e) {
      var that = this;
      var adv = that.data.msg;
      if (adv.appid) {
        wx.navigateToMiniProgram({
          appId: adv.appid,
          path: adv.path,
        });
        return;
      }
      else if (adv.path.indexOf('http') >= 0) {
        wx.setStorageSync('advurl', adv.path);
        wx.navigateTo({
          url: '../web/web',
        })
      } else {
        wx.reLaunch({
          url: adv.path,
        })
      }
    },
    goThere:function(e){
    	var that = this;
    	var dataset = e.currentTarget.dataset;
    	var index = dataset.index;
    	var adv = that.data.adv;
    	adv = adv[index];
    	if(adv.appid){
    		wx.navigateToMiniProgram({
    	        appId: adv.appid,
    	        path: adv.link,
    	    });
    	    return;
    	}
    	else{
    		wx.setStorageSync('advurl', adv.link);
    	    wx.navigateTo({
    	        url: '../web/web',
    	    })
    	}
    },
    getAgreement:function(){
    	var that = this;
    	if(that.data.agreement){
        that.setData({ openAD: !this.data.openAD})
        return false;
      }
      wx.showLoading({
        title: '加载中',
      })
    	app.util.request({
        	url: 'entry/wxapp/getAgreement',
        	data: {
        		m: 'junsion_challeng',
        		t: 1,
        	},
        	success: function (res) {
        		if(res.data.agreement){
              WxParse.wxParse('agreecontent' , 'html', res.data.agreement, that,10);
            }
            wx.hideLoading();
            that.setData({
              agreement: true, openAD: !this.data.openAD
            });
        	},
        });
    },
    goBuy:function(e){
    	var that = this;
    	var dataset = e.currentTarget.dataset;
    	var selkey = dataset.index;
    	var paytype = 1;
		wx.showLoading();
		app.util.request({
            url: 'entry/wxapp/CreateOrder',
            data: {
                m : 'junsion_challeng',
                t : 1,
                openid:that.data.openid,
                paytype:paytype,
                selkey:selkey,
            },
            success: function (res) {
              wx.hideLoading();
              if(res.data.code == 1){
            	  res = res.data.res;
            	  res['success'] = function(){
            		  checkorder(res.orderid,that)
                  };
                  wx.requestPayment(res);
              }else{
            	  wx.showModal({title:res.data.msg,showCancel:false});
              }
            },
        });
    },
    moreGroup:function(){
    	var that = this;
        if (groupLoading) return;
        groupLoading = true;
        that.setData({groupHasMore:true});
        wx.showLoading();
        app.util.request({
            url: 'entry/wxapp/groupMem',
            data: {
                m : 'junsion_challeng',
                t : 1,
                scroll:true,
                page:++that.data.grouppage,
                mid : that.data.mid,
                game: that.data.gametype,
            },
            success: function (res) {
              wx.hideLoading();
              if(res.data.status == 1){
            	  groupLoading = false;
                  that.setData({
                	  group_mems: that.data.group_mems.concat(res.data.group_mems),
                	  groupHasMore:false
                  });
              }else{
            	  that.setData({groupHasMore:true});
              }
            },
        });
    },
    moreWill:function(){
    	var that = this;
        if (willLoading) return;
        willLoading = true;
        that.setData({willHasMore:true});
        wx.showLoading();
        app.util.request({
            url: 'entry/wxapp/willmem',
            data: {
                m : 'junsion_challeng',
                t : 1,
                scroll:true,
                page:++that.data.willpage,
            },
            success: function (res) {
              wx.hideLoading();
              if(res.data.status == 1){
            	  willLoading = false;
                  that.setData({
                	  will_mems: that.data.will_mems.concat(res.data.will_mems),
                	  willHasMore:false
                  });
              }else{
            	  that.setData({willHasMore:true});
              }
            },
        });
    },
    scroll : function(e){
        if(e.detail.scrollTop > 100){
          this.setData({
                floorstatus: true
          });
          }else {
          this.setData({
              floorstatus: false
          });
          }
      },
      //加载更多
    onReachBottom: function(e) {
        var that = this;
        if (giftLoading) return;
        giftLoading = true;
        wx.showLoading();
        app.util.request({
            url: 'entry/wxapp/gift',
            data: {
                m : 'junsion_challeng',
                t : 1,
                scroll:true,
                page:++that.data.giftpage,
            },
            success: function (res) {
              wx.hideLoading();
              if(res.data.status == 1){
            	giftLoading = false;
                that.setData({
                	gifts: that.data.gifts.concat(res.data.gifts),
                });
              }
            },
        });
      },  
    //打开公告
    showAD:function(e){
    	this.getAgreement();
    },
    //获得更多机会
    showChance:function(e){
        this.setData({
            openChance: !this.data.openChance
        })
    },
    //tab分类
    chooseType:function(e){
        var idx = e.currentTarget.dataset.idx;
        this.setData({
            activeType:idx
        })
    },
    onCol: function (res) {
        var that = this;
        app.util.request({
          url: 'entry/wxapp/FID',
          data: { m: 'junsion_challeng', openid: that.data.openid, formId: res.detail.formId },
        });
    },
    goPlay:function (){
    	var that = this;
    	var avatar = that.data.avatar;
    	if(!avatar){
    		wx.openSetting({
  			  success(res){
  				  wx.authorize({
  					  scope:'scope.userInfo',
  					  success:function(res){
  					  wx.getUserInfo({
  					  success: function (info) {
                      		var nickname = info.userInfo.nickName;
                      		var avatar = info.userInfo.avatarUrl;
                      		that.setData({avatar:avatar});
                      		app.util.request({
                                url: 'entry/wxapp/Info',
                                data: { 
                                	m: 'junsion_challeng', 
                                	openid: that.data.openid, 
                                	nickname: nickname,
                                	avatar: avatar,
                                	},
                                success: function (res) {
                                	that.goPlay();
                                }
                              });
  							}
  						});
  					  },
  					  fail:function(res){
  						  console.log(res);
  					  }
  				  });
  			  },
  			  fail:function(res){
  				  console.log(res)
  			  }
  		  });
    	}
    	else{
    		if(parseInt(that.data.gametype)==1){
      		    var url = '../splay/splay';
      	    }
      	    else if(parseInt(that.data.gametype)==2){
      	    	var url = '../tplay/tplay';
      	    }
      	    else if(parseInt(that.data.gametype)==3){
      	    	var url = '../fplay/fplay';
      	    }
      	    else if(parseInt(that.data.gametype)==4){
      	    	var url = '../wplay/wplay';
      	    }
      	    else if(parseInt(that.data.gametype)==5){
      	    	var url = '../xplay/xplay';
      	    }
      	    else if(parseInt(that.data.gametype)==6){
      	    	var url = '../cplay/cplay';
      	    }
      	    else if(parseInt(that.data.gametype)==7){
      	    	var url = '../yplay/yplay';
      	    }
      	    else if(parseInt(that.data.gametype)==8){
      	    	var url = '../qplay/qplay';
      	    }
      	    else if(parseInt(that.data.gametype)==9){
    		    var url = '../zplay/zplay';
    	    }
      	    else{
      		    var url = '../play/play';
      	    }
        	wx.showLoading();
        	wx.navigateTo({
              url: url
          })
    	}
    },
    hideLibao:function(){
    	var that = this;
    	that.setData({
    		libao: 1
        });
    	that.goPlay();
    },
    /*checkpage2 start*/
    startTimer: function (e) {
      let startTime = Date.now()
      let isRuning = this.data.isRuning
      let timerType = e.target.dataset.type
      let showTime = this.data[timerType + 'Time']
      let keepTime = showTime * 60 * 1000
      let logName = this.logName || defaultLogName[timerType]

      if (!isRuning) {
        this.timer = setInterval((function () {
          this.updateTimer()
          this.startNameAnimation()
        }).bind(this), 1000)
      } else {
        this.stopTimer()
      }

      this.setData({
        isRuning: !isRuning,
        completed: false,
        timerType: timerType,
        remainTimeText: showTime + ':00',
        taskName: logName
      })

      this.data.log = {
        name: logName,
        startTime: Date.now(),
        keepTime: keepTime,
        endTime: keepTime + startTime,
        action: actionName[isRuning ? 'stop' : 'start'],
        type: timerType
      }

      this.saveLog(this.data.log)
    },

    startNameAnimation: function () {
      let animation = wx.createAnimation({
        duration: 450
      })
      animation.opacity(0.2).step()
      animation.opacity(1).step()
      this.setData({
        nameAnimation: animation.export()
      })
    },

    stopTimer: function () {
      // reset circle progress
      this.setData({
        leftDeg: initDeg.left,
        rightDeg: initDeg.right
      })

      // clear timer
      this.timer && clearInterval(this.timer)
    },

    updateTimer: function () {
      let log = this.data.log
      let now = Date.now()
      let remainingTime = Math.round((log.endTime - now) / 1000)
      let H = formatTime(Math.floor(remainingTime / (60 * 60)) % 24, 'HH')
      let M = formatTime(Math.floor(remainingTime / (60)) % 60, 'MM')
      let S = formatTime(Math.floor(remainingTime) % 60, 'SS')
      let halfTime

      // update text
      if (remainingTime > 0) {
        let remainTimeText = (H === "00" ? "" : (H + ":")) + M + ":" + S
        this.setData({
          remainTimeText: remainTimeText
        })
      } else if (remainingTime == 0) {
        this.setData({
          completed: true
        })
        this.stopTimer()
        return
      }

      // update circle progress
      halfTime = log.keepTime / 2
      if ((remainingTime * 1000) > halfTime) {
        this.setData({
          leftDeg: initDeg.left - (180 * (now - log.startTime) / halfTime)
        })
      } else {
        this.setData({
          leftDeg: -135
        })
        this.setData({
          rightDeg: initDeg.right - (180 * (now - (log.startTime + halfTime)) / halfTime)
        })
      }
    },

    changeLogName: function (e) {
      this.logName = e.detail.value
    },

    saveLog: function (log) {
      var logs = wx.getStorageSync('logs') || []
      logs.unshift(log)
      wx.setStorageSync('logs', logs)
    }
		  /*checkpage2 end */
})